//
//  LoginController.swift
//  YiYaoHui
//
//  Created by HM on 15/12/2.
//  Copyright © 2015年 TMPercy. All rights reserved.
//

import UIKit
import Alamofire

protocol LoginDelegate {
    func loginSuccess()
}

class LoginController: UIViewController {
    
    
    @IBOutlet weak var cancelLoginButton: UIButton!
    
    @IBOutlet weak var registerButton: UIButton!
    @IBOutlet weak var loginButton: UIButton!
    
    @IBOutlet weak var accountTF: UITextField!
    @IBOutlet weak var cipherTF: UITextField!
    
    @IBOutlet weak var loginView: UIView!
    
    var delegate: LoginDelegate!
    
    let baseURL = "http://112.74.131.194:8080/MedicineProject/App/login"
    let personalController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("personalController")

    var identifierForVendor:String?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        cancelLoginButton.setTitle("返回", forState:.Normal)
        registerButton.layer.cornerRadius = 5
        loginButton.layer.cornerRadius = 5
        accountTF.delegate = self
        cipherTF.delegate = self
        
        loginView.layer.borderWidth = 1.0
        loginView.layer.borderColor = UIColor(red: 235/255, green: 235/255, blue: 235/255, alpha: 1).CGColor
        
        tabBarController?.tabBar.hidden = true
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardShow:", name: UIKeyboardWillShowNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardHide:", name: UIKeyboardWillHideNotification, object: nil)
    }
    
    override func viewWillAppear(animated: Bool) {
        navigationController?.navigationBarHidden = true
    }
    
    @IBAction func chooseRegister(sender: AnyObject) {
        dismissKeyboard()
        performSegueWithIdentifier("register", sender: self)
    }
    
    @IBAction func forgetCipher(sender: AnyObject) {
        performSegueWithIdentifier("forgetCipher", sender: self)
    }
    
    
    //取消登陆
    @IBAction func cancelLogin(sender: AnyObject) {
        self.navigationController?.popViewControllerAnimated(true)
    }
    
    //登陆请求
    @IBAction func login(sender: AnyObject) {
        
        dismissKeyboard()
        
        identifierForVendor = UIDevice.currentDevice().identifierForVendor?.UUIDString
        
        if (accountTF.text != "" && cipherTF.text != "") {
            
            let parameters = ["account":accountTF.text!,"password":cipherTF.text!,"device":"2","deviceId":identifierForVendor!]
            Alamofire.request(.POST, baseURL, parameters: parameters, encoding: .URL, headers: nil).responseJSON { (_, _, result) -> Void in
                
                //先判断返回的值是否为空，不为空就执行这一步
                if let  value = result.value {
                    //再判断返回的值是success还是fail,success就可以登陆成功，执行登陆成功后的操作
                    let state = value["result"] as! String
                    if state == "success" {
                        
                        //随时保存登陆状态，同步到ns user defaults: 登陆成功的话，bool设成true。
                        NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
                            NSUserDefaults.standardUserDefaults().setBool(true, forKey: "loginState")
                            NSUserDefaults.standardUserDefaults().setValue(self.accountTF.text, forKey: "account")
                            NSUserDefaults.standardUserDefaults().setValue(self.cipherTF.text, forKey: "cipher")
                            NSUserDefaults.standardUserDefaults().synchronize()
                            
                            self.delegate.loginSuccess()
                            self.navigationController?.pushViewController(self.personalController, animated: true)
                        })
                    }
                    //如果返回fail继续检查帐号、密码是否有误。
                    else {
                        self.showAlert("登录失败", message: "帐号或密码错误")
                    }
                }
                //为空就检查帐号和密码是否有误
                else {
                    self.showAlert("登录失败", message: "帐号或密码错误")
                }
            }
        }
        else {
            self.showAlert("信息输入不正确", message: "帐号和密码均不能为空")
        }
    }
    
    func showAlert(prompt: String, message: String) {
        let alert = UIAlertController(title: prompt, message: message, preferredStyle: UIAlertControllerStyle.Alert)
        let action = UIAlertAction(title: "确定", style: UIAlertActionStyle.Default, handler: nil)
        alert.addAction(action)
        self.presentViewController(alert, animated: true, completion: nil)
    }
    
}

//text field 的
extension LoginController: UITextFieldDelegate {
    
    //弹起键盘的
    func dismissKeyboard() {
        accountTF.resignFirstResponder()
        cipherTF.resignFirstResponder()
    }

    
    
    
    //点击空白处的响应。
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        dismissKeyboard()
        
        accountTF.resignFirstResponder()
        cipherTF.resignFirstResponder()
        
        accountTF.text = accountTF.text!.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: " "))
        cipherTF.text = cipherTF.text!.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: " "))

    }
    //按return键的响应。
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        //收键盘
        accountTF.resignFirstResponder()
        cipherTF.resignFirstResponder()
        //保存文字信息
        
        accountTF.text = accountTF.text!.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: " "))
        cipherTF.text = cipherTF.text!.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: " "))
    
        return true
    }
}

extension LoginController {
    func keyBoardShow(notification: NSNotification) {
        
        let screenHeight = UIScreen.mainScreen().bounds.height
        let keyBoardFrame = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
        let offsetY = keyBoardFrame.height
        print(offsetY)
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.frame.origin.y = screenHeight - (425.0 + offsetY + 30)
        }
    }
    
    func keyBoardHide(notification: NSNotification) {
        
        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.frame.origin.y = 0.0
        }
    }
}